﻿using System;
using System.Web;

namespace PageAdmin.Utils
{
    /// <summary>
    /// cookie帮助类
    /// </summary>
    public class CookieHelper
    {

        /// <summary>
        /// 获取cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static string Get(string cookieName)
        {
            if(HttpContext.Current==null)return null;
            if (HttpContext.Current.Request.Cookies[cookieName] == null)
            {
                return null;
            }
            else
            {
                return HttpContext.Current.Request.Cookies[cookieName].Value;
            }
        }

        /// <summary>
        /// 添加cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="cookieValue"></param>
        /// <param name="seconds"></param>
        /// <param name="path"></param>
        public static void Add(string cookieName, string cookieValue,long? seconds=null,string path=null,string domain=null)
        {
            if (HttpContext.Current == null) return;
            HttpCookie addCookie = new HttpCookie(cookieName);
            //addCookie.HttpOnly = true;
            addCookie.Value = cookieValue;
            if(path!=null)
            {
                addCookie.Path = path;
            }
            else
            {
                addCookie.Path = "/";
            }
            if (seconds != null)
            {
                addCookie.Expires = DateTime.Now.AddSeconds((long)seconds);
            }
            if (domain!=null)
            {
                addCookie.Domain =StringHelper.DomainFormat(domain,false);
            }
            HttpContext.Current.Response.AppendCookie(addCookie);
        }

        /// <summary>
        /// cookie解密
        /// </summary>
        public static void Remove(string name)
        {
            if (HttpContext.Current == null) return;
            if (Get(name) == null)
            {
                return;
            }
            HttpCookie removeCookie = new HttpCookie(name);
            removeCookie.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.AppendCookie(removeCookie);
        }
    }
}
